package com.jsmile.cloud.tradecenter.order.repo;

import java.util.Collection;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.jsmile.cloud.tradecenter.order.dao.OrderDao;
import com.jsmile.cloud.tradecenter.order.model.Order;
import com.jsmile.cloud.tradecenter.order.model.OrderAddress;
import com.jsmile.cloud.tradecenter.order.model.OrderDiscount;
import com.jsmile.cloud.tradecenter.order.model.OrderProduct;

import lombok.AllArgsConstructor;

@Component
@AllArgsConstructor
@Transactional(readOnly = false)
public class OrderRepository extends ServiceImpl<OrderDao, Order> {

    private final OrderProductRepository orderProductRepository;
    private final OrderDiscountRepository orderDiscountRepository;
    private final OrderAddressRepository orderAddressRepository;

    @Override
    public boolean saveBatch(Collection<Order> entityList) {
        if (CollectionUtils.isEmpty(entityList)) {
            return false;
        }
        List<OrderProduct> orderProducts = Lists.newArrayList();
        List<OrderDiscount> orderDiscounts = Lists.newArrayList();
        List<OrderAddress> orderAddresses = Lists.newArrayList();
        entityList.forEach(x -> {
            if (!CollectionUtils.isEmpty(x.getOrderProducts())) {
                orderProducts.addAll(x.getOrderProducts());
            }
            if (!CollectionUtils.isEmpty(x.getOrderDiscounts())) {
                orderDiscounts.addAll(x.getOrderDiscounts());
            }
            if (null != x.getOrderAddress()) {
                orderAddresses.add(x.getOrderAddress());
            }
        });
        orderAddressRepository.saveBatch(orderAddresses);
        orderDiscountRepository.saveBatch(orderDiscounts);
        orderProductRepository.saveBatch(orderProducts);
        return super.saveBatch(entityList);
    }

}
